var tags = {};

tags.Tag = function(entry) {
  this.entry = entry;
  this.title = entry.title.$t;
  this.id = entry.id.$t;
  this.photoIds = [];
  this.link = {
    'communityPhotos': util.getLink(entry.link, 'alternate').href,
    'myPhotos': util.getLink(entry.link, 'alternate').href.replace('psc=G', 'psc=S')
  };

};

/**
 * Callback for processing the JSON feed returned by the DocList API.
 * @param {string} response The server's response.
 * @param {XMLHttpRequest} xhr The xhr request that was made.
 */
tags.processTagListResults = function(response, xhr) {
  if (xhr.status != 200) {
    util.handleError(xhr, response);
    return;
  } else {
    requestFailureCount = 0;
  }

  var data = JSON.parse(response);

  for (var i = 0, entry; entry = data.feed.entry[i]; ++i) {
    var tag = new tags.Tag(entry);
    bgPage.tags[tag.title] = tag;
  }

  var nextLink = util.getLink(data.feed.link, 'next');
  if (nextLink) {
    gdocs.getDocumentList(nextLink.href); // Fetch next page of results.
  } else {
    tags.renderDocList();
      // finished
  }
};

tags.processPhotoTagListResults = function(response, xhr) {
  if (xhr.status != 200) {
    util.handleError(xhr, response);
    return;
  } else {
    requestFailureCount = 0;
  }

  var data = JSON.parse(response);

  for (var i = 0, entry; entry = data.feed.entry[i]; ++i) {
    var tag = new tags.Tag(entry);
    if(!bgPage.selectedTags[tag.title]) {
	bgPage.selectedTags[tag.title] = tag;
    }
    var photoId = data.feed.gphoto$id.$t;
    tag.photoIds.push(photoId);
    $.each(bgPage.selectedPhotos, function (selectedPhotoId) {
	if (selectedPhotoId == photoId) {
	    bgPage.selectedPhotos[selectedPhotoId].tags.push(tag.title);
	}
    });
  }

  var nextLink = tags.getLink(data.feed.link, 'next');
  if (nextLink) {
    gdocs.getDocumentList(nextLink.href); // Fetch next page of results.
  } else {
//    tags.renderDocList();
      // finished
  }
};

/**
 * Presents the in-memory documents that were fetched from the server as HTML.
 */
tags.renderDocList = function() {
  util.hideMsg();

  var sortedTags = Object.keys(bgPage.tags);
  var filteredTags = [];

  sortedTags.sort(function (l,r) {return l.toUpperCase().localeCompare(r.toUpperCase());});

  var selectedTagKeys = Object.keys(bgPage.selectedTags);

  var filter = $("#tagFilter").val();

  if (filter) {
      filter = filter.toUpperCase();
      for(var idx in sortedTags) {
         var sortedTag = sortedTags[idx];
	  if (sortedTag.toUpperCase().indexOf(filter) >= 0) {
	      filteredTags.push(sortedTag);
	  }
      }
  } else {
      filteredTags = sortedTags;
  }

  for (var idx in selectedTagKeys) {
      filteredTags = jQuery.grep(filteredTags, function(value) {
	  return value != selectedTagKeys[idx];
      });
  }

  $('#tags').html('');
  $('#photoTags').html('');

  for (var i = 0, tag; tag = filteredTags[i]; ++i) {
    // If we have an arbitrary file, use generic file icon.

        var div = $('<div class="photoTag"/>')
                       .attr('data-index', i)
		        .text(tag);
	$('#tags').append(div);

  }

  for (var key in selectedTagKeys) {
        var tag = bgPage.selectedTags[selectedTagKeys[key]];
    // If we have an arbitrary file, use generic file icon.

        var div = $('<div class="photoTag"/>')
                       .attr('data-index', i)
		        .text(tag.title);
	$('#photoTags').append(div);

  }

  $('.photoTag').dblclick(function(ev) {tags.moveTag(ev.target);});
};

tags.moveTag = function(el) {
   var title = $(el).text();
   if($(el).parent().closest("div").attr("id") == "photoTags") {
     delete bgPage.selectedTags[title];
   } else {
     bgPage.selectedTags[title] = bgPage.tags[title];
   }
   tags.renderDocList();
};

/**
 * Fetches the user's document list.
 * @param {string?} opt_url A url to query the doclist API with. If omitted,
 *     the main doclist feed uri is used.
 */
tags.getDocumentList = function(opt_url, callback) {
  var url = opt_url || null;

  var params = {
    'headers': {
      'GData-Version': '3.0'
    }
  };

  if (!url) {
    util.displayMsg('Fetching your tags');
    bgPage.setIcon({'text': '...'});

    bgPage.tags = {}; // Clear document list. We're doing a refresh.

    url = bgPage.DOCLIST_FEED;
    params['parameters'] = {
      'alt': 'json'
    };
  } else {
    util.displayMsg($('#butter').text() + '.');

    var parts = url.split('?');
    if (parts.length > 1) {
      url = parts[0]; // Extract base URI. Params are passed in separately.
      params['parameters'] = util.unstringify(parts[1]);
    }
  }

  bgPage.oauth.sendSignedRequest(url, callback, params);
};
/*
tags.deleteTagsFromPhotos = function(photos, callback) {
    if(photos.length) {
       tags.deleteTagsFromPhoto(photos[0], function () {
          tags.deleteTagsFromPhotos(photos.slice(1), callback);
       });
    } else {
	callback();
    }
};

tags.deleteTagsFromPhoto = function (photo, callback) {
    if (photo.tags.length) {
	var currentTag = photo.tags[0];
        tags.deleteTagFromPhoto(photo, currentTag, function(xhr, resp) {
	    photo.tags = photo.tags.slice(1);
//            $("#progress").text("deleting p: " + pIdx + "/" + photoCnt + " t: " + tIdx + "/" + tagCnt);
            tags.deleteTagsFromPhoto(photo, callback);
        });
    } else {
	callback();
    }
};

tags.deleteTagFromPhoto = function(photo, tag, callback) {
  var params = {
    'headers': {
      'GData-Version': '3.0'
    }
  };
  var photoId = photo.id;

  util.displayMsg($('#butter').text() + '.');

  var url = "https://picasaweb.google.com/data/entry/api/user/default/albumid/" + photo.albumId + "/photoid/" + photoId + "/tag/" + encodeURIComponent(tag);

  var parts = url.split('?');
  if (parts.length > 1) {
    url = parts[0]; // Extract base URI. Params are passed in separately.
    params['parameters'] = util.unstringify(parts[1]);
  }
  params['method'] = "DELETE";

  bgPage.oauth.sendSignedRequest(url, callback, params);
};
*/
tags.addTagsToPhotos = function(photosToTag, tagsToBeAdded) {
    if (photosToTag.length) {
	tags.addTagsToPhoto(photosToTag[0], tagsToBeAdded, function (xhr, resp) {
	    tags.addTagsToPhotos(photosToTag.slice(1), tagsToBeAdded);
	});
    }
};

tags.addTagsToPhoto_old = function(photoToTag, tagsToBeAdded, callback) {
   if (tagsToBeAdded.length) {
       var currentTag = tagsToBeAdded[0];
       photoToTag.tags.push(currentTag);
       tags.addTagToPhoto(photoToTag.id, currentTag,  function(xhr, resp) {
	   tags.addTagsToPhoto(photoToTag, tagsToBeAdded.slice(1), callback);
       });
   } else {
       callback();
   }
};

tags.addTagsToPhoto = function(photoToTag, tagsToBeAdded, callback) {
  var photoId = photoToTag.id;
  var tags = tagsToBeAdded.join(',');

  var params = {
    'headers': {
      'GData-Version': '3.0',
      'If-Match' : '*',
      'Content-Type' : "application/xml"
    },
    'method' : 'PATCH'
  };

  util.displayMsg($('#butter').text() + '.');

  var url = "https://picasaweb.google.com/data/entry/api/user/default/albumid/" + photoToTag.albumId + "/photoid/" + photoId + "?kind=album&access=all&alt=json";

  var parts = url.split('?');
  if (parts.length > 1) {
    url = parts[0]; // Extract base URI. Params are passed in separately.
    params['parameters'] = util.unstringify(parts[1]);
  }

  params['body'] = //"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            "<entry xmlns='http://www.w3.org/2005/Atom' xmlns:media='http://search.yahoo.com/mrss/' xmlns:gphoto='http://schemas.google.com/photos/2007'>" 
           + "<media:group>" 
           + " <media:keywords>" 
           +  tags // XXX need to XML encode
           + " </media:keywords>" 
           + "</media:group>"
//           + "<category scheme=\"http://schemas.google.com/g/2005#kind\" term=\"http://schemas.google.com/photos/2007#photo\" />"
           + "</entry>";

  bgPage.oauth.sendSignedRequest(url, callback, params);
};



tags.apply = function() {
    var photos = util.values(bgPage.selectedPhotos);

//    tags.deleteTagsFromPhotos(photos, function () {
       tags.addTagsToPhotos(photos, Object.keys(bgPage.selectedTags));
//    });
};

